package com.example.vo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 带数据的自定义响应结构
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class SysResultData extends SysResult implements Serializable {

	private static final long serialVersionUID = 1L;
	
	/**
	 * 响应数据
	 */
	private List<?> data;

	public SysResultData() {
	}

	public SysResultData(Integer status, String msg, List<?> data) {
		super(status, msg);
		this.data = data;
	}
	
	public SysResultData(Integer status) {
		super(status);
	}

	public SysResultData(List<?> data) {
		this(STATUS_SUCCEED, MESSAGES.get(STATUS_SUCCEED), data);
	}

	public Object getData() {
		return data;
	}

	public void setData(List<?> data) {
		this.data = data;
	}

	public static SysResultData build(Integer status, String msg, List<?> data) {
		return new SysResultData(status, msg, data);
	}

	public static SysResultData ok(List<?> data) {
		return new SysResultData(data);
	}

	public static SysResultData ok() {
		return new SysResultData(STATUS_SUCCEED);
	}
	
	public static SysResultData ok(Object obj) {
		List<Object> list = new ArrayList<>();
		list.add(obj);
		return new SysResultData(list);
	}
	
	private static SysResultData build(int status, String msg, List<?> list) {
		return new SysResultData(status, msg, list);
	}
	
	/**
	 * Object是集合转化
	 * 
	 * @param jsonData json数据
	 * @param clazz 集合中的类型
	 * @return
	 */
	public static SysResultData formatToList(String jsonData, Class<?> clazz) {
		return format(jsonData, clazz);
	}

	/**
	 * 将json结果集转化为SysResult对象
	 * @param jsonData json数据
	 * @param clazz data属性的类型
	 * @return
	 */
	private static SysResultData format(String jsonData, Class<?> clazz) {
		try {
			if (clazz == null) {
				return MAPPER.readValue(jsonData, SysResultData.class);
			} else {
				JsonNode jsonNode = MAPPER.readTree(jsonData);
				JsonNode data = jsonNode.get("data");
				List<?> list = null;
				if (data.isArray() && data.size() > 0) {
					list = MAPPER.readValue(data.traverse(),
							MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
				}
				return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), list);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public String toString() {
		super.toString();
		return "SysResultData [data=" + data + "]";
	}

	
	
}
